import datetime
from django.shortcuts import render, redirect, get_object_or_404
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from web import models
from web.forms.bug import BugModelForm, BugCommentModelForm
from django.db.models import Q


@login_required
def bug_list(request, project_id):
    """ 项目BUG列表 """
    project = get_object_or_404(models.Project, id=project_id)
    # 检查用户是否有权限访问该项目
    if not project.projectuser_set.filter(user=request.user).exists():
        return redirect('project_list')

    # 获取筛选参数
    search_query = request.GET.get('search', '')
    status_filter = request.GET.get('status', '')
    priority_filter = request.GET.get('priority', '')
    assign_to_filter = request.GET.get('assign_to', '')
    sort_by = request.GET.get('sort', 'create_datetime')
    sort_order = request.GET.get('order', 'desc')

    # 基本查询
    bugs = models.Bug.objects.filter(project_id=project_id)

    # 应用搜索筛选
    if search_query:
        bugs = bugs.filter(title__icontains=search_query)

    # 应用状态筛选
    if status_filter:
        bugs = bugs.filter(status_id=status_filter)

    # 应用优先级筛选
    if priority_filter:
        bugs = bugs.filter(priority_id=priority_filter)

    # 应用指派筛选
    if assign_to_filter:
        if assign_to_filter == 'unassigned':
            bugs = bugs.filter(assign_to__isnull=True)
        else:
            bugs = bugs.filter(assign_to_id=assign_to_filter)

    # 应用排序
    sort_field = sort_by
    if sort_order == 'desc':
        sort_field = f'-{sort_by}'

    bugs = bugs.order_by(sort_field)

    # 获取所有状态和优先级选项，用于模板中的筛选表单
    status_options = models.BugStatus.objects.filter(project=project)
    priority_options = models.BugPriority.objects.filter(project=project)
    user_options = project.projectuser_set.all().values('user_id', 'user__username')

    # 准备筛选和排序参数，用于模板中的表单
    filter_params = {
        'search_query': search_query,
        'status_filter': status_filter,
        'priority_filter': priority_filter,
        'assign_to_filter': assign_to_filter,
        'sort_by': sort_by,
        'sort_order': sort_order
    }

    return render(request, 'bug_list.html', {
        'project': project,
        'bugs': bugs,
        'status_options': status_options,
        'priority_options': priority_options,
        'user_options': user_options,
        'filter_params': filter_params
    })


@login_required
def bug_add(request, project_id):
    """ 创建BUG """
    project = get_object_or_404(models.Project, id=project_id)
    # 检查用户是否有权限访问该项目
    if not project.projectuser_set.filter(user=request.user).exists():
        return redirect('project_list')

    if request.method == 'GET':
        form = BugModelForm(project_id=project_id)
        return render(request, 'bug_add.html', {
            'project': project,
            'form': form
        })

    form = BugModelForm(data=request.POST, project_id=project_id)
    if form.is_valid():
        bug_obj = form.save(commit=False)
        bug_obj.project = project
        bug_obj.creator = request.user
        bug_obj.save()
        return redirect('bug_detail', project_id=project_id, bug_id=bug_obj.id)

    return render(request, 'bug_add.html', {
        'project': project,
        'form': form
    })


@login_required
def bug_detail(request, project_id, bug_id):
    """ BUG详情 """
    project = get_object_or_404(models.Project, id=project_id)
    bug = get_object_or_404(models.Bug, id=bug_id, project_id=project_id)

    # 检查用户是否有权限访问该项目
    if not project.projectuser_set.filter(user=request.user).exists():
        return redirect('project_list')

    # 处理评论表单
    comment_form = BugCommentModelForm()
    if request.method == 'POST' and 'comment' in request.POST:
        comment_form = BugCommentModelForm(data=request.POST)
        if comment_form.is_valid():
            comment_obj = comment_form.save(commit=False)
            comment_obj.bug = bug
            comment_obj.creator = request.user
            comment_obj.save()
            return redirect('bug_detail', project_id=project_id, bug_id=bug_id)

    # 获取BUG的所有评论
    comments = models.BugComment.objects.filter(bug_id=bug_id).order_by('create_datetime')

    return render(request, 'bug_detail.html', {
        'project': project,
        'bug': bug,
        'comments': comments,
        'comment_form': comment_form
    })


@login_required
def bug_edit(request, project_id, bug_id):
    """ 编辑BUG """
    project = get_object_or_404(models.Project, id=project_id)
    bug = get_object_or_404(models.Bug, id=bug_id, project_id=project_id)

    # 检查用户是否有权限访问该项目
    if not project.projectuser_set.filter(user=request.user).exists():
        return redirect('project_list')

    if request.method == 'GET':
        form = BugModelForm(instance=bug, project_id=project_id)
        return render(request, 'bug_edit.html', {
            'project': project,
            'bug': bug,
            'form': form
        })


@login_required
def bug_batch_action(request, project_id):
    """ BUG批量操作 """
    project = get_object_or_404(models.Project, id=project_id)
    # 检查用户是否有权限访问该项目
    if not project.projectuser_set.filter(user=request.user).exists():
        return redirect('project_list')

    if request.method == 'POST':
        action = request.POST.get('action')
        bug_ids = request.POST.getlist('bug_ids')

        if not action or not bug_ids:
            return redirect('bug_list', project_id=project_id)

        # 批量删除
        if action == 'delete':
            models.Bug.objects.filter(
                id__in=bug_ids,
                project_id=project_id
            ).delete()
        # 批量更改状态
        elif action == 'change_status':
            status_id = request.POST.get('status_id')
            if status_id:
                models.Bug.objects.filter(
                    id__in=bug_ids,
                    project_id=project_id
                ).update(status_id=status_id)
        # 批量更改优先级
        elif action == 'change_priority':
            priority_id = request.POST.get('priority_id')
            if priority_id:
                models.Bug.objects.filter(
                    id__in=bug_ids,
                    project_id=project_id
                ).update(priority_id=priority_id)
        # 批量指派
        elif action == 'assign_to':
            assign_to_id = request.POST.get('assign_to_id')
            if assign_to_id:
                models.Bug.objects.filter(
                    id__in=bug_ids,
                    project_id=project_id
                ).update(assign_to_id=assign_to_id)

    return redirect('bug_list', project_id=project_id)

    form = BugModelForm(data=request.POST, instance=bug, project_id=project_id)
    if form.is_valid():
        form.save()
        return redirect('bug_detail', project_id=project_id, bug_id=bug_id)

    return render(request, 'bug_edit.html', {
        'project': project,
        'bug': bug,
        'form': form
    })


@login_required
def bug_delete(request, project_id, bug_id):
    """ 删除BUG """
    project = get_object_or_404(models.Project, id=project_id)
    bug = get_object_or_404(models.Bug, id=bug_id, project_id=project_id)

    # 检查用户是否有权限访问该项目
    if not project.projectuser_set.filter(user=request.user).exists():
        return JsonResponse({'status': False, 'error': '无权限访问该项目'})

    # 只有创建者或项目管理员可以删除BUG
    if bug.creator != request.user and project.creator != request.user:
        return JsonResponse({'status': False, 'error': '只有创建者或项目管理员可以删除BUG'})

    bug.delete()
    return JsonResponse({'status': True})


@login_required
def bug_status_update(request, project_id, bug_id):
    """ 更新BUG状态 """
    if request.method != 'POST':
        return JsonResponse({'status': False, 'error': '请求方式错误'})

    project = get_object_or_404(models.Project, id=project_id)
    bug = get_object_or_404(models.Bug, id=bug_id, project_id=project_id)

    # 检查用户是否有权限访问该项目
    if not project.projectuser_set.filter(user=request.user).exists():
        return JsonResponse({'status': False, 'error': '无权限访问该项目'})

    status_id = request.POST.get('status_id')
    if not status_id:
        return JsonResponse({'status': False, 'error': '请选择状态'})

    try:
        status = models.BugStatus.objects.get(id=status_id, project_id=project_id)
    except models.BugStatus.DoesNotExist:
        return JsonResponse({'status': False, 'error': '状态不存在'})

    bug.status = status
    bug.save()
    return JsonResponse({'status': True, 'status_name': status.name})